const multer = require('multer');
const fs = require('fs')

//创建磁盘存储对象
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        //先定义一个动态的目录
        let s = 'public/upload/'
        const date = new Date()
        s += date.getFullYear() + '/'
        s += (date.getMonth() + 1) + '/'
        s += date.getDate() + '/'
        //s = 'public/2023/1/4/'
        // { recursive: true }表示允许mkdir一次创建多级目录
        fs.mkdirSync(s, { recursive: true })
        cb(null, s)
    },
    filename: function (req, file, cb) {
        //文件名的指定，要求文件名越长越好，目的是避免重复
        const date = new Date()
        let s = '';
        s += date.getFullYear();
        s += ('0' + (date.getMonth() + 1)).slice(-2)
        s += ('0' + (date.getDate())).slice(-2)
        s += ('0' + (date.getHours())).slice(-2)
        s += ('0' + (date.getMinutes())).slice(-2)
        s += ('0' + (date.getSeconds())).slice(-2)
        s += ('00' + (date.getMilliseconds())).slice(-3)
        s += Math.round(Math.random() * 1000)
        const arr = file.originalname.split('.')
        s += '.' + arr[arr.length - 1]
        cb(null, s)

    }
});

//创建上传存储的实例对象
const upload = multer({
    storage,
})

module.exports = upload